package com.zt.ztyh.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import com.zt.ztyh.entity.ZtyhRecording;
import com.zt.ztyh.pojo.Occupation;
import com.zt.ztyh.pojo.User;
import com.zt.ztyh.pojo.UserByInfo;
import com.zt.ztyh.pojo.UserVo;
import com.zt.ztyh.service.OccupationService;
import com.zt.ztyh.service.open.CardService;
import com.zt.ztyh.service.open.RecordService;
import com.zt.ztyh.vo.common.Result;
import com.zt.ztyh.vo.common.ResultCodeEnum;
import com.zt.ztyh.dto.LoginDto;
import com.zt.ztyh.dto.UserDto;
import com.zt.ztyh.vo.LoginVo;
import com.zt.ztyh.vo.UserInfoVo;
import com.zt.ztyh.vo.ValidateCodeVo;
import com.zt.ztyh.service.UserService;
import io.swagger.v3.oas.annotations.media.Schema;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * @author 卫相阳
 * @date 2024/4/2 18:50
 * OverSion04
 */
@RestController
@RequestMapping("ztyh/login")
public class LoginController {
    @Autowired
    private UserService userService;
    @Autowired
    private RedisTemplate<String, String> redisTemplate;
    @Autowired
    private OccupationService occupationService;
    @Autowired
    private RecordService recordService;
    @Autowired
    private CardService cardService;

    /**
     * 登录接口
     * @param loginDto
     * @return
     */
    @PostMapping("/login")
    @Schema(description = "登录接口")
    public Result<LoginVo> login(@RequestBody LoginDto loginDto){
        LoginVo loginVo = userService.login(loginDto);
        return Result.build(loginVo, ResultCodeEnum.SUCCESS);
    }


    /**
     * 手机号登录
     * @param loginDto
     * @return
     */
    @PostMapping("/phoneCode")
    @Schema(description = "手机号登录")
    public Result<LoginVo> phoneLogin(@RequestBody LoginDto loginDto){
        LoginVo loginVo = userService.phoneLogin(loginDto);
        return Result.build(loginVo, ResultCodeEnum.SUCCESS);
    }
    /**
     * 更具用户名查询是否存在
     */
    @GetMapping("/usernameOne")
    @Schema(description = "根据用户名查询用户")
    public Result<User> getUserByName(String username){
        System.out.println("userName:" + username);
        User user = userService.getUserByName(username);
        return Result.build(user, ResultCodeEnum.SUCCESS);
    }

    @PutMapping("/forgetPassword")
    @Schema(description = "忘记密码")
    public Result<User> forgetPassword(@RequestBody UserDto userDto){
        User user = userService.forgetPassword(userDto);
        return Result.build(user, ResultCodeEnum.SUCCESS);
    }
    /**
     * 查询手机号是否存在
     */
    @GetMapping("/phoneOne")
    @Schema(description = "查询手机号")
    public Result<User> getUserByPhone(String phone){
        User user = userService.getUserByPhone(phone);
        return Result.build(user, ResultCodeEnum.SUCCESS);
    }
    /**
     * 余额的加减
     * @param token
     * @param userByInfo
     * @return
     */
    @PutMapping("/unLoan")
    @Schema(description = "余额的加减")
    public boolean updateUserinfo(@RequestHeader("token") String token,@RequestBody UserInfoVo userByInfo){
        return userService.updateUnLoan(token, userByInfo);
    }

    /**
     * 获取用户的信息
     * 首先拿到token 从请求头中拿到
     * 根据token从redis中取出user信息 然后返回给客户端进行展示
     * @param token
     * @return
     */
    @GetMapping("/getUserinfo")
    @Schema(description = "获取用户的信息")
    public Result<UserInfoVo> getUserinfo(@RequestHeader("token") String token) {
        System.out.println("token:" + token);
        //根据token从redis中取出user信息 赋值
        UserInfoVo userInfoVo = userService.getUserInfo(token);
        return Result.build(userInfoVo, ResultCodeEnum.SUCCESS);
    }

    /**
     * 获取图片验证码接口
     * 封装一个验证码VO类
     * @Schema(description = "验证码key")
     * private String codeKey ;        // 验证码的key
     * @Schema(description = "验证码value")
     * private String codeValue ;      // 图片验证码对应的字符串数据
     * @return
     */
    @GetMapping("/validateCode")
    @Schema(description = "获取图片验证码接口")
    public Result<ValidateCodeVo> getValidateCode(){
        ValidateCodeVo validateCodeVo = userService.getValidateCode();
        return Result.build(validateCodeVo, ResultCodeEnum.SUCCESS);
    }

    /**
     * 获取短信验证码
     * 将验证码放到redis中
     * @param phone
     * @return
     */
    @GetMapping("/send")
    @Schema(description = "获取短信验证码")
    public Result<LoginVo> send(String phone){
        String codes="";
        //随机6位数
        Random random = new Random();
        int randomNumber = random.nextInt(900000) + 100000;
        codes=String.valueOf(randomNumber);
        //封装map
        Map<String,Object> map=new HashMap<>(10);
        map.put("codes",codes);
        //发送验证码
//        boolean b=userService.send(phone,map);
        boolean b=true;
        if(b){
            //存入redis，有效期1分钟
            this.redisTemplate.opsForValue().set(phone+"_"+codes, randomNumber+"",1, TimeUnit.MINUTES);
            return Result.build("发送成功", ResultCodeEnum.SUCCESS);
        }else{
            return Result.build("发送失败", ResultCodeEnum.DATA_ERROR);
        }
    }
    /**
     * 用户退出
     * 根据toker 从redis中删除用户信息
     */
    @GetMapping("/logout")
    @Schema(description = "用户退出")
    //每小时执行一次
    @Scheduled(cron = "")
    public Result<String> logout(@RequestHeader("token")String token){
        userService.logout(token);
        return Result.build("退出成功", ResultCodeEnum.SUCCESS);
    }
    /**
     * 用户注册
     * 封装一个VO类
     * @Schema(description = "用户名")
     * private String username ;
     * @Schema(description = "密码")
     * private String password ;
     * @Schema(description = "手机号")
     * private String phone ;
     * 输入手机号，账号，密码，验证码
     * 验证码正确，手机号不存在，账号不存在，密码正确，注册成功
     * 验证码错误，手机号存在，账号存在，密码错误，注册失败
     * 手机号存在了 提示手机号已存在（进行手机号唯一验证）然后跳转到登录页面
     * @return
     */
    @PostMapping("/register")
    @Schema(description = "用户注册")
    public Result<UserDto> register(@RequestBody UserDto userdto){
        boolean register = userService.register(userdto);
        return register ? Result.build("注册", ResultCodeEnum.SUCCESS) : Result.build("注册", ResultCodeEnum.SYSTEM_ERROR);
    }
    /**
     * 用户修改登录密码
     * 输入原密码 新密码
     * 密码正确，修改成功
     * 原密码错误，修改失败
     * @return
     */
    @PutMapping("/updatePassword")
    @Schema(description = "修改密码")
    public String updatePassword(@RequestHeader("token")String token,@RequestBody UserVo userVo){
        User user = this.userService.updatePassword(token,userVo);
        return "修改成功";
    }
    /**
     * 用户修改个人信息（个人信息不包含支付密码，登录密码，手机号，账号，余额）
     * 验证码正确，手机号存在，账号存在，修改成功
     * 验证码错误，修改失败
     * @return
     */
    @PutMapping("/updateUserinfo")
    @Schema(description = "修改个人信息")
    public String updateUserinfo(@RequestHeader("token")String token,@RequestBody UserByInfo userByInfo){
        User user= userService.updateUserinfo(token,userByInfo);
        return "修改成功";
    }

    //实名认证
    @PostMapping("/GotoIdentity")
    @Schema(description = "实名认证")
    public Result gotoGotoIdentity(@RequestHeader("token")String token,@RequestBody UserInfoVo userInfoVo){
        UserInfoVo userInfoVo1 = userService.updateUnId(token,userInfoVo);
        return Result.build(userInfoVo1, ResultCodeEnum.SUCCESS);
    }
    @GetMapping("/Tocname/{id}")
    @Schema(description = "职业")
    public Result<User> Tocname(@PathVariable("id")Long id){
        Occupation occupation = this.occupationService.byId(id);
        System.out.println("查询了职业:::");
        System.out.println(occupation);
        return Result.build(occupation, ResultCodeEnum.SUCCESS);
    }
    @PostMapping("/addMoney")
    @Schema(description = "充值")
    public Result<UserInfoVo> addMoney(@RequestHeader("token")String token,@RequestBody UserInfoVo userInfoVo){
        UserInfoVo userInfoVo1 = userService.addMoney(token,userInfoVo);
        return Result.build(userInfoVo1, ResultCodeEnum.SUCCESS);
    }
    @GetMapping("/getMyunNum/{id}")
    @Schema(description = "余额查询")
    public Result getMyunNum(@RequestHeader("token")String token,@PathVariable("id")Long id){
        UserInfoVo userInfoVo = userService.getMyunNum(token,id);
        return Result.build(userInfoVo, ResultCodeEnum.SUCCESS);
    }

    /**
     * 充值时银行卡的扣款
     * @param banalce
     * @param cardnumber
     * @return
     */
    @PutMapping("/banalceNumber")
    @Schema(description = "银行卡扣款")
    public Result banalceNumber(String banalce,String cardnumber){
        System.out.println("请求了这个借口");
        Result result = cardService.account(banalce, cardnumber);
        return Result.build(result, ResultCodeEnum.SUCCESS);
    }
    @PutMapping("/outCard")
    @Schema(description = "银行卡扣款")
    public Result outCard(String banalce,String cardnumber){
        System.out.println("提现获取的余额");
        System.out.println(banalce);
        System.out.println("提现获取的银行卡号");
        System.out.println(cardnumber);
        Result result = cardService.chong(banalce, cardnumber);
        return Result.build(result, ResultCodeEnum.SUCCESS);
    }
    @PostMapping("/cardinfo")
    @Schema(description = "信息存储")
    public Result cardinfo(@RequestBody ZtyhRecording ztyhRecording){
        System.out.println(ztyhRecording.getMoneyout());
        System.out.println(ztyhRecording.getAmount());
        System.out.println(ztyhRecording.getMoneyin());
        System.out.println(ztyhRecording.getOperatortype());
        return Result.build(recordService.addRecording(ztyhRecording), ResultCodeEnum.SUCCESS);
    }
    @GetMapping("/userid/{id}")
    @Schema(description = "用户id查询")
    public User userid(@PathVariable("id")Long id){
        User user = this.userService.getById(id);
        return user;
    }
    /**
     * 支付密码确认
     */
    @GetMapping("/passwordUn")
    public Result<User> passwordUn(Long id,String password){
        //截取密码中间的逗号
        String substring = password.substring(1, 6);
        System.out.println(substring);
        return Result.build(substring, ResultCodeEnum.SUCCESS);
    }

    /**
     * 查询银行卡余额是否充足
     * @param cardnumber
     * @return
     */
    @GetMapping("/showCardBalance")
    public Result showCardBalance(@RequestParam("cardnumber") String cardnumber) {
        Result balance = this.cardService.balance(cardnumber);
        return Result.build(balance, ResultCodeEnum.SUCCESS);
    }
    @GetMapping("/getPhoneUsersname")
    public Result getPhoneUsersname(@RequestParam("realname") String realname,@RequestParam("phone") String phone) {
        User user = this.userService.getPhoneUsersname(realname,phone);
        return Result.build(user, ResultCodeEnum.SUCCESS);
    }

    /**
     * 转账时用户余额的添加
     * @param phone
     * @param amount
     * @return
     */
    @PutMapping("/addMoneys")
    public Result addMoneys(@RequestParam("phone")String phone,@RequestParam("amount")BigDecimal amount) {
        int user = this.userService.updateUnAmount(phone, amount);
        return Result.build(user, ResultCodeEnum.SUCCESS);
    }

    @GetMapping("/GetUserListTime")
    public Result GetUserListTime(@RequestParam("userId") Long userId,
                                  @RequestParam("openType") int openType
    ) {
        List<ZtyhRecording> recordings = this.recordService.getUserListTime(userId,openType);
        return Result.build(recordings, ResultCodeEnum.SUCCESS);
    }
}
